package com.woniuxy.commons.utile;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class BeanCopyUtil {
    public static <T>T copyOne(Object source,Class<T> clazz){
        T t = null;
        try {
            t = clazz.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        BeanUtils.copyProperties(source,t);
        return t;
    }

    public static <T>List<T> copyList(List list, Class<T> clazz){
        ArrayList<T> newList = new ArrayList<T>();
        T t = null;
        for (Object o : list) {
            try {
                t = clazz.newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            BeanUtils.copyProperties(o,t);
            newList.add(t);
        }

        return newList;
    }

    public static <T> Page<T> copyPages(Page sources, Class<T> clazz){
        Page<T> page = new Page<>();
        ArrayList<T> records = new ArrayList<>();
        try {
            for (Object source : sources.getRecords()) {
                T t = clazz.newInstance();
                BeanUtils.copyProperties(source,t);
                records.add(t);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        page.setRecords(records);
        page.setTotal(sources.getTotal());
        page.setPages(sources.getPages());
        page.setCurrent(sources.getCurrent());
        page.setSize(sources.getSize());
        return page;
    }

    public static <T>Page copyPage(List<T> source,Integer pageNum,Integer pageSize){
        Page<T> page = new Page<>();
        page.setTotal(source.size());
        page.setSize(pageSize);
        page.setRecords(source);
        page.setCurrent(pageNum);
        return page;
    }

    public static Long parseDateString(String time,String pattern){
        try {
            SimpleDateFormat sd = new SimpleDateFormat(pattern);
            return sd.parse(time).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String  parseDateLogin(Long time, String pattern){
        SimpleDateFormat sd = new SimpleDateFormat(pattern);
        return sd.format(new Date(time));
    }
}
